import axios from 'axios'
import store from '../store'
import router from '@/router/index.js'
import { updateTokenInterface } from "@/api/my.js";
const ajax = axios.create({
  baseURL: 'http://toutiao.itheima.net' // 根地址 二次封装
})

// 请求拦截器  对token做统一处理
ajax.interceptors.request.use(config => {
  // console.log(config);
  // 如果vuex中有token中就在请求头中Authorization 携带给后台
  if (store.state.token) {
    config.headers.Authorization = `Bearer ${store.state.token}`
  } else {
    config.headers.Authorization = `Bearer ${store.state.refresh_token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器  对返回错误或者token过期做统一处理
ajax.interceptors.response.use(resp => {
  // http 以 2 3开头 成功回调
  return resp
}, async error => {
  // http 以 4 5开头 失败回调
  // console.log(error);
  if (error.response.data.message === 'refresh_token失效') {
    store.commit('setToken', '')
    store.commit('setRefresh_token', '')
    router.replace({
      path: '/Login?from=' + router.currentRoute.path
    })

  }
  if (error.response.status === 401) {
    // window.localStorage.setItem('token', resq.data.data.token)
    store.commit('setToken', '')
    const resq = await updateTokenInterface()
    store.commit('setToken', resq.data.data.token)
    return ajax(error.config)
  }
  return Promise.reject(error)
})

export default ajax
